using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using Fuse8.DomainFramework.Domain;

namespace Fuse8.DomainFramework.DataAccess.SqlDatabase
{
    internal class SqlSchemaBuilderWithChain:ISqlSchemaBuilderChain
    {
        readonly List<ISqlSchemaBuilder> chain = new List<ISqlSchemaBuilder>();
        private ISqlSchemaBuilder defaultBuilder;

        public IList<SqlColumn> GetColumns<T>(SqlConnection connection)
        {
            return GetColumns(typeof (T), connection);
        }

        public IList<SqlColumn> GetColumns(Type type, SqlConnection connection)
        {
            foreach (var builder in chain)
            {
                IList<SqlColumn> result = builder.GetColumns(type, connection);
                if (result != null)
                {
                    return result;
                }
            }

            return defaultBuilder.GetColumns(type, connection);
        }

        public IList<SqlProcedureParameter> GetStoredProcedureParameters(SqlConnection connection, SqlTransaction transaction, string sp)
        {
            foreach (var builder in chain)
            {
                IList<SqlProcedureParameter> result = builder.GetStoredProcedureParameters(connection, transaction, sp);
                if (result != null)
                {
                    return result;
                }
            }

            return defaultBuilder.GetStoredProcedureParameters(connection, transaction, sp);
        }

        public IList<Type> GetUpdateParts<T>()
        {
            foreach (var builder in chain)
            {
                IList<Type> result = builder.GetUpdateParts<T>();
                if (result != null)
                {
                    return result;
                }
            }

            return defaultBuilder.GetUpdateParts<T>();
        }

        public void Add(ISqlSchemaBuilder builder)
        {
            chain.Add(builder);
        }

        public void AddDefault(ISqlSchemaBuilder sqlSchemaBuilder)
        {
            defaultBuilder = sqlSchemaBuilder;
        }
    }
}